package com.imti.retrofitdemo;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import okhttp3.FormBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity
{

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView()
    {
        Button btnSendGet = findViewById(R.id.btn_send_get);
        Button btnSendPost = findViewById(R.id.btn_send_post);
        Button btnSendRxGet = findViewById(R.id.btn_send_rxjava_get);
        Button btnSendCityWeather = findViewById(R.id.btn_send_rxjava_city_weather);

        btnSendCityWeather.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                BaseApplication.weatherRequest
                    .requestCityWeather("西安")
                    .map(weatherResponseBaseObjRequest ->
                    {
                        WeatherCityInfoModel model = new WeatherCityInfoModel();
                        model.setTemp(
                            weatherResponseBaseObjRequest.getResult().getRealtime()
                                .getTemperature());
                        model.setType(
                            weatherResponseBaseObjRequest.getResult().getRealtime()
                                .getInfo());
                        model.setAqi(weatherResponseBaseObjRequest.getResult().getRealtime()
                                         .getAqi());
                        return model;
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(weatherCityInfoModel ->
                    {
                        Log.d(TAG, "天气类型：" + weatherCityInfoModel.getType());
                        Log.d(TAG, "当前气温：" + weatherCityInfoModel.getTemp());
                        Log.d(TAG, "当前空气指数：" + weatherCityInfoModel.getAqi());
                    });

            }
        });

        List<String> cityList = new ArrayList<>();

        btnSendRxGet.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                BaseApplication.weatherRequest
                    .requestCityListByRx("8149094547f3e900f1ea47e6a25de938")
                    .flatMap(new Func1<BaseListRequest<CityItem>, Observable<CityItem>>()
                    {
                        @Override
                        public Observable<CityItem> call(
                            BaseListRequest<CityItem> cityItemBaseListRequest)
                        {
                            return Observable.from(cityItemBaseListRequest.getResult());
                        }
                    })
                    .map(new Func1<CityItem, String>()
                    {
                        @Override
                        public String call(CityItem cityItem)
                        {
                            return cityItem.getCity();
                        }
                    })
                    //事件过滤
                    .filter(new Func1<String, Boolean>()
                    {
                        @Override
                        public Boolean call(String s)
                        {
                            if (cityList.isEmpty())
                            {
                                return true;
                            }

                            return !cityList.contains(s);
                        }
                    })
                    //线程调度器，开启子线程，将事件序列加入到子线程中并执行
                    .subscribeOn(Schedulers.io())
                    //RxAndroid的库，线程切换至UI线程
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<String>()
                    {
                        @Override
                        public void onCompleted()
                        {
                            for (String city : cityList)
                            {
                                Log.d(TAG, "城市名称：" + city);
                            }

                        }
                        @Override
                        public void onError(Throwable e)
                        {

                        }
                        @Override
                        public void onNext(String s)
                        {
                            cityList.add(s);
                        }
                    });
                //订阅并消费事件
//                    .subscribe(new Action1<BaseListRequest<CityItem>>()
//                    {
//                        @Override
//                        public void call(BaseListRequest<CityItem> cityItemBaseListRequest)
//                        {
//                            for (CityItem city : cityItemBaseListRequest.getResult())
//                            {
//                                Log.d(TAG, "RxJava+Retrofit使用线程调度器发送网络请求，结果为："
//                                               + city.getDistrict());
//                            }
//                        }
//                    });

            }
        });

        btnSendPost.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                FormBody body = new FormBody.Builder()
                                    .add("key", "8149094547f3e900f1ea47e6a25de938")
                                    .build();

                BaseApplication.weatherRequest.requestCityListPost(body)
                    .enqueue(new Callback<BaseListRequest<CityItem>>()
                    {
                        @Override
                        public void onResponse(Call<BaseListRequest<CityItem>> call,
                            Response<BaseListRequest<CityItem>> response)
                        {
                            CityItem[] result = response.body().getResult();

                            for (int i = 0; i < result.length; i++)
                            {
                                Log.d(TAG, "id = " + result[i].getId() +
                                               " province = " + result[i].getProvince() +
                                               " city = " + result[i].getCity() +
                                               " district = " + result[i].getDistrict());
                            }
                        }
                        @Override
                        public void onFailure(Call<BaseListRequest<CityItem>> call, Throwable t)
                        {

                        }
                    });
            }
        });

        btnSendGet.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                BaseApplication.weatherRequest
                    .requestCityList("8149094547f3e900f1ea47e6a25de938")
                    .enqueue(new Callback<BaseListRequest<CityItem>>()
                    {
                        @Override
                        public void onResponse(Call<BaseListRequest<CityItem>> call,
                            Response<BaseListRequest<CityItem>> response)
                        {
                            CityItem[] result = response.body().getResult();

                            for (int i = 0; i < result.length; i++)
                            {
                                Log.d(TAG, "id = " + result[i].getId() +
                                               " province = " + result[i].getProvince() +
                                               " city = " + result[i].getCity() +
                                               " district = " + result[i].getDistrict());
                            }
                        }
                        @Override
                        public void onFailure(Call<BaseListRequest<CityItem>> call, Throwable t)
                        {
                            Log.d(TAG, "请求报错");
                        }
                    });
            }
        });
    }
}